<template>
  <div class="supplier-order-con table-gl-w">
    <div class="search-w">
      <FilterTable :filterItem="filterItem" ref="filterTable" :isReset="true" @search="searchByVal" />
    </div>
    <div class="table-gl-con">
      <TableWrap style="flex: 1" @refresh="getList">
        <template #headerLeft></template>
        <template #tableBody>
          <a-table class="table-two-line" ref="tableListref" :span-method="spanMethodAll" row-key="id" :expandable="expandable" :default-expand-all-rows="true" :loading="loading" @selection-change="selectColumn" :row-selection="rowSelection" :bordered="false" :columns="tableColumns" :data="tableList" size="mini" :pagination="false" :scroll="{ y: '100%' }">
            <template #columns>
              <a-table-column v-for="(item, index) of tableColumns" :fixed="item.fixed" :key="index" :align="item.align" :width="item.width" :title="item.title" :data-index="item.dataIndex">
                <template v-if="item.dataIndex == 'sort'" #cell="{ rowIndex }">
                  <p>{{ rowIndex + 1 }}</p>
                </template>

                <template v-else-if="item.dataIndex == 'purchaseNo'" #cell="{ record }">
                  <!-- <div class="flex-c-sb" style="display: flex; align-items: center"> -->
                  <div style="display: flex; align-items: center">
                    <div class="order-w flex">
                      <div class="order-detail-item" style="width: 200px">
                        <div class="flex-c">
                          <span class="label">交货单号：</span>
                          <span class="highlight cursor" @click="toDetail(record)">{{ record.billNo }}</span>
                          <CopyText class="popup-edit-icon-hover" style="margin-left: 5px" :val="record.billNo" />
                        </div>
                        <p>
                          <span class="label">交货仓：</span>
                          <span>{{ record.deliveryWarehouseName }}({{ record.deliveryWarehouseCode }})</span>
                        </p>
                      </div>
                      <div class="order-detail-item" style="width: 200px">
                        <p><span class="label">经销商：</span>{{ record.companyName }}</p>
                        <p><span class="label">交货日期：</span>{{ $setTime(record.gmtDelivery, 'YYYY/MM/DD HH:mm') }}</p>
                      </div>
                      <div class="order-detail-item" style="width: 200px">
                        <p><span class="label">签收人：</span>{{ record.signUname }}</p>
                        <p><span class="label">签收日期：</span>{{ $setTime(record.gmtSign, 'YYYY/MM/DD HH:mm') }}</p>
                      </div>
                      <div class="order-detail-item" style="width: 140px">
                        <p><span class="label">交货数：</span>{{ record.deliveryAmt }}</p>
                        <p><span class="label">实际交货数：</span>{{ record.deliveryRealAmt }}</p>
                      </div>
                      <div class="order-detail-item" style="width: 140px">
                        <p><span class="label">已入库数：</span>{{ record.warehouseRealAmt }}</p>
                        <p><span class="label">退回数：</span>{{ record.warehouseReturnAmt }}</p>
                      </div>
                      <div class="order-detail-item" style="width: 140px">
                        <p><span class="label">实交货值：</span>{{ record.deliveryValue }}</p>
                        <p><span class="label">入库货值：</span>{{ record.inventoryValue }}</p>
                      </div>
                      <div class="order-detail-item" style="width: 150px">
                        <div class="flex">
                          <span class="label" style="flex-shrink: 0">备注：</span>
                          <p style="width: 100px">
                            <TextLimit>{{ record.remark }}</TextLimit>
                          </p>
                        </div>
                      </div>
                    </div>
                    <div class="flex-c" style="position: relative">
                      <a-space style="margin-top: -8px">
                        <a-tag color="arcoblue" size="small" bordered>{{ statusMap[record.status] }}</a-tag>
                        <div style="width: 60px; text-align: right">
                          <a-button type="text" @click="toDetail(record)">详情</a-button>
                        </div>
                        <a-dropdown @select="handleSelect($event, record)">
                          <icon-more class="table-btn-more" />
                          <template #content>
                            <a-doption value="去配货" v-if="(record.status == '10' || record.status == '70') && $authPass('procurement.supplier.delivery.distribute')">去配货</a-doption>
                            <a-doption value="编辑交货单" v-if="(record.status == '10' || record.status == '70') && $authPass('procurement.supplier.delivery.edit')">编辑交货单</a-doption>
                            <a-doption value="确认出库" v-if="record.status == '20' && $authPass('procurement.supplier.delivery.outbound')">确认出库</a-doption>
                            <!-- <a-doption value="确认出库">确认出库</a-doption> -->
                            <a-doption value="删除" v-if="(record.status == '10' || record.status == '70') && $authPass('procurement.supplier.delivery.delete')">删除</a-doption>
                            <a-doption value="打印" v-if="$authPass('procurement.supplier.delivery.print')">打印</a-doption>
                            <a-doption value="日志">日志</a-doption>
                          </template>
                        </a-dropdown>
                      </a-space>
                      <div v-if="record.status == 70" style="position: absolute; bottom: -13px; left: 0"> 供应商拒绝：{{ record.refuseMsg ? record.refuseMsg : '--' }} </div>
                    </div>
                  </div>
                </template>
                <template #title v-else-if="item.dataIndex == 'ssku'">
                  <a-popover content="默认从供应商产品上获取关联的SKU，如果供应商产品没有则空着">
                    <p>
                      <span>供应商SKU</span>
                      <icon-question-circle />
                    </p>
                  </a-popover>
                </template>
                <template #title v-else-if="item.dataIndex == 'sku'">
                  <a-popover content="经销商SKU是指卖家采购单上的SKU">
                    <p>
                      <span>经销商SKU</span>
                      <icon-question-circle />
                    </p>
                  </a-popover>
                </template>
                <template #title v-else-if="item.dataIndex == 'deliveryAmt'">
                  <a-popover content="生成交货单时填写的交货数量">
                    <p>
                      <span>交货数</span>
                      <icon-question-circle />
                    </p>
                  </a-popover>
                </template>
                <template #title v-else-if="item.dataIndex == 'deliveryRealAmt'">
                  <a-popover content="经销商签收交货单时实际收到的数量">
                    <p>
                      <span>实际交货数</span>
                      <icon-question-circle />
                    </p>
                  </a-popover>
                </template>
                <template #title v-else-if="item.dataIndex == 'deliveryDiffAmt'">
                  <a-popover content="交货单签收的实际数量跟交货单数量的差额">
                    <p>
                      <span>交货差额</span>
                      <icon-question-circle />
                    </p>
                  </a-popover>
                </template>
                <template #title v-else-if="item.dataIndex == 'warehouseRealAmt'">
                  <a-popover content="实际入到仓库的数量">
                    <p>
                      <span>已入库数</span>
                      <icon-question-circle />
                    </p>
                  </a-popover>
                </template>
                <template #title v-else-if="item.dataIndex == 'warehouseReturnAmt'">
                  <a-popover content="仓库签收入库单时遇到次品退回的数量">
                    <p>
                      <span>退回数</span>
                      <icon-question-circle />
                    </p>
                  </a-popover>
                </template>
                <template #title v-else-if="item.dataIndex == 'price'">
                  <a-popover content="采购单填写的单价">
                    <p>
                      <span>采购单价</span>
                      <icon-question-circle />
                    </p>
                  </a-popover>
                </template>
                <template #title v-else-if="item.dataIndex == 'deliveryValue'">
                  <a-popover content="实交金额=单价*实际交货数">
                    <p>
                      <span>实交金额</span>
                      <icon-question-circle />
                    </p>
                  </a-popover>
                </template>
                <template #title v-else-if="item.dataIndex == 'inventoryValue'">
                  <a-popover content="入库金额=单价*已入库数">
                    <p>
                      <span>入库金额</span>
                      <icon-question-circle />
                    </p>
                  </a-popover>
                </template>
              </a-table-column>
            </template>
            <template #expand-row="{ record }" :colspan="27">
              <a-table class="table-singe-line" row-class="child-row" :show-header="false" row-key="id" :bordered="false" :columns="tableColumns" :data="record.billItems" size="mini" :pagination="false">
                <template #columns>
                  <a-table-column :width="10" />
                  <a-table-column :width="40" />
                  <a-table-column v-for="(item, index) of tableColumns" :key="index" :fixed="item.fixed" :align="item.align" :width="item.width" :title="item.title" :data-index="item.dataIndex">
                    <template v-if="item.dataIndex == 'sort'" #cell> </template>
                    <template v-else-if="item.dataIndex == 'purchaseNo'" #cell="option">
                      <TextHidden :rowsWidth="100" position="top" class="highlight">{{ option.record.purchaseNo }}</TextHidden>
                    </template>
                    <template v-else-if="item.dataIndex == 'img'" #cell="option">
                      <ImgPopover :src="option.record.productImg">
                        <template #con>
                          <a-image width="40" height="40" fit="contain" :src="option.record.productImg" />
                        </template>
                      </ImgPopover>
                    </template>
                    <template v-else-if="item.dataIndex == 'productName'" #cell="option">
                      <TextLimit :rows="2" position="top">{{ option.record.productName }}</TextLimit>
                    </template>
                    <template v-else-if="item.dataIndex == 'sku'" #cell="option">
                      <TextLimit :rows="1">{{ option.record.sku || '--' }}</TextLimit>
                    </template>
                    <template v-else-if="item.dataIndex == 'productSpecs'" #cell="option">
                      <TextLimit position="top">{{ getSpecName(option.record) }}</TextLimit>
                    </template>
                    <template v-else-if="item.dataIndex == 'rate'" #cell="option">
                      <TextLimit :rows="1">{{ option.record.rate }}%</TextLimit>
                    </template>

                    <template v-else-if="item.dataIndex == 'price'" #cell="option">
                      <div class="highlight">{{ option.record.priceType ? '含税' : '不含税' }}</div>
                      <div>￥{{ option.record.price }}</div>
                    </template>
                    <template v-else-if="item.dataIndex == 'deliveryValue'" #cell="option">
                      <div class="highlight">{{ option.record.priceType ? '含税' : '不含税' }}</div>
                      <div>￥{{ option.record.deliveryValue }}</div>
                    </template>
                    <template v-else-if="item.dataIndex == 'inventoryValue'" #cell="option">
                      <div class="highlight">{{ option.record.priceType ? '含税' : '不含税' }}</div>
                      <div>￥{{ option.record.inventoryValue }}</div>
                    </template>
                  </a-table-column>
                </template>
              </a-table>
            </template>
          </a-table>
        </template>
      </TableWrap>
      <div class="pagination-footer" v-if="statusCurrentIndex != 11">
        <a-pagination size="mini" :page-size-options="[20, 50, 100, 200, 500]" show-total show-page-size :total="pageNation.total" :default-page-size="pageNation.pageSize" :current="pageNation.pageNum" style="float: right" @page-size-change="sizeChange" @change="changePage" />
      </div>
    </div>
  </div>

  <AllocateGoods ref="allocateGoods" :list="selectRowList" @save="getList" />
  <EditDeliveryOrder ref="editDeliveryOrder" :list="selectRowList" @save="getList" />
  <SubmitOutHouse ref="submitOutHouse" :list="selectRowList" @save="getList" />
  <deliveryOrderDetail ref="deliveryOrderDetail" :info="info" />
  <CommonLogsDialog v-if="showLogDialog" api="findSupplierDeliveryLogPage" :id="info.id" :isShow="showLogDialog" @closed="showLogDialog = false" />
</template>

<script lang="ts">
  import { defineComponent, reactive, ref, toRef, toRefs, watch } from 'vue'
  import { Message, Modal } from '@arco-design/web-vue'
  import { findWarehouseListByParam } from '@/api/warehouse'
  import { findSupplierDeliveryPage, cancelSupplierDeliveryOrder } from '@/api/supplier'
  import { useRouter } from 'vue-router'
  import FilterTable from '@/components/TableFilter.vue'
  import TableWrap from '@/components/TableWrap.vue'
  import AllocateGoods from './allocateGoods.vue'
  import EditDeliveryOrder from './editDeliveryOrder.vue'
  import SubmitOutHouse from './submitOutHouse.vue'
  import deliveryOrderDetail from './deliveryOrderDetail.vue'
  import CommonLogsDialog from '@/components/Log/logsDialog.vue'

  export default defineComponent({
    components: {
      FilterTable,
      TableWrap,
      AllocateGoods,
      EditDeliveryOrder,
      SubmitOutHouse,
      deliveryOrderDetail,
    },
    props: ['currentIndex', 'getNum'],
    setup(props: any, { emit }) {
      const allocateGoods = ref()
      const editDeliveryOrder = ref()
      const submitOutHouse = ref()
      const deliveryOrderDetail = ref()
      const route = useRouter()
      const data: any = reactive({
        showLogDialog: false,
        filterItem: [
          {
            type: 'input_keyword',
            key: 'billNos',
            keyItems: [{ label: '采购单号', value: 'billNos' }],
            keyWidth: '100',
            value: ref(),
            placeholder: '请输入',
            label: '采购单号',
            width: 160,
            isMultiple: true,
          },
          {
            type: 'input_keyword',
            key: 'sskus',
            keyItems: [
              { label: 'SKU', value: 'sskus' },
              { label: '产品名称', value: 'productName' },
              // { label: '客户SKU', value: '客户SKU' },
            ],
            keyWidth: '100',
            value: ref(),
            placeholder: '请输入',
            label: 'SKU',
            width: 160,
            isMultiple: true,
          },
          {
            key: 'warehouseCode',
            label: '交货仓库',
            value: ref(),
            type: 'select',
            width: 140,
            optionItems: [],
            attrs: {
              'allow-search': true,
            },
          },
          {
            key: 'companyName',
            label: '经销商',
            value: ref(),
            type: 'input_search',
            width: 140,
          },
          {
            type: 'keyword_date_range',
            key: 'gmtPurchase',
            keyItems: [
              { label: '交货日期', value: 'gmtPurchase' },
              { label: '创建日期', value: 'gmtPurchase0' },
              { label: '签收日期', value: 'gmtCreate' },
              { label: '入库日期', value: 'gmtLatestShip' },
            ],
            keyWidth: '110',
            value: ref(),
            placeholder: '请输入',
            label: '提交日期',
            width: 200,
          },
        ],
        tableColumns: [
          {
            title: '序号',
            dataIndex: 'sort',
            width: 40,
          },
          {
            title: '采购单',
            dataIndex: 'purchaseNo',
            width: 140,
          },
          {
            title: '图片',
            dataIndex: 'img',
            width: 60,
          },
          {
            title: '产品名称',
            dataIndex: 'productName',
            width: 140,
          },
          {
            title: 'SKU',
            dataIndex: 'ssku',
            width: 140,
          },
          {
            title: '经销商SKU',
            dataIndex: 'sku',
            width: 140,
          },
          {
            title: '规格',
            dataIndex: 'productSpecs',
            width: 140,
          },
          {
            title: '交货数',
            dataIndex: 'deliveryAmt',
            width: 70,
          },
          {
            title: '实际交货数',
            dataIndex: 'deliveryRealAmt',
            width: 120,
          },
          {
            title: '交货差额',
            dataIndex: 'deliveryDiffAmt',
            width: 120,
          },
          {
            title: '已入库数',
            dataIndex: 'warehouseRealAmt',
            width: 120,
          },
          {
            title: '退回数',
            dataIndex: 'warehouseReturnAmt',
            width: 120,
          },
          {
            title: '税率',
            dataIndex: 'rate',
            width: 120,
          },
          {
            title: '含税单价',
            dataIndex: 'price',
            width: 120,
          },
          {
            title: '实交货值',
            dataIndex: 'deliveryValue',
            width: 120,
          },
          {
            title: '入库货值',
            dataIndex: 'inventoryValue',
            width: 120,
          },
        ],
        tableList: [],
        searchValue: {},
        pageNation: { total: 0, pageSize: 20, pageNum: 1 },
        loading: false,
        expandable: {
          title: '',
          defaultExpandAllRows: true,
          expandedRowKeys: [],
          width: 10,
        },
        rowSelection: {
          type: 'checkbox',
          showCheckedAll: true,
          onlyCurrent: false,
        },
        statusMap: {
          '10': '待配货',
          '20': '待出库',
          '30': '待签收',
          '40': '待入库',
          '50': '入库中',
          '60': '已入库',
          '70': '已拒收',
        },
        selectRowList: [],
        info: {},
      })

      const searchByVal = (info: any) => {
        data.searchValue = {}
        data.searchValue = info
        if (data.searchValue.startDate) {
          data.searchValue.startDate = `${data.searchValue.startDate} 00:00:00`
          data.searchValue.endDate = `${data.searchValue.endDate} 23:59:59`
        }
        data.pageNation.pageNum = 1
        getList()
      }

      const changePage = (val: number) => {
        data.pageNation.pageNum = val
        getList()
      }

      const sizeChange = (val: number) => {
        data.pageNation.pageNum = 1
        data.pageNation.pageSize = val
        getList()
      }

      const getList = async () => {
        let params = {
          ...data.searchValue,
          status: props.currentIndex,
          pageNum: data.pageNation.pageNum,
          pageSize: data.pageNation.pageSize,
        }
        data.loading = true
        // data.loading = false
        const res: any = await findSupplierDeliveryPage(params)
        let arr = res?.data?.records || []
        data.tableList = arr
        data.pageNation.total = res?.data?.total
        data.expandable.expandedRowKeys = data.tableList.map((el: any) => el.id)
        data.loading = false
        props.getNum(params)
      }

      const getWareHouseList = async () => {
        const res = await findWarehouseListByParam()
        let arr = res?.data
        arr.map((e: any) => {
          e.label = e.warehouseName
          e.value = e.warehouseCode
        })
        data.filterItem[2].optionItems = arr
      }

      // 合并单元格
      const spanMethodAll = (option: any) => {
        let { column } = option
        if (column.dataIndex === 'img') {
          return { rowspan: 1, colspan: 23 }
        }
      }

      const handleSelect = (type: string, item: any) => {
        switch (type) {
          case '去配货':
            data.selectRowList = []
            data.selectRowList.push(item)
            allocateGoods.value.visible = true
            break
          case '编辑交货单':
            data.selectRowList = []
            data.selectRowList.push(item)
            editDeliveryOrder.value.visible = true
            break
          case '确认出库':
            data.selectRowList = []
            data.selectRowList.push(item)
            submitOutHouse.value.visible = true
            break
          case '删除':
            del(item.id)
            break
          case '日志':
            data.info = item
            data.showLogDialog = true
            break
          case '打印':
            window.sessionStorage.setItem('deliveryPrintPDFId', item.id)
            route.push({
              path: '/supplier/order/components/supplierPrintPDF',
              // query: {
              //   id: item.id,
              // },
            })

            break
        }
      }

      const del = (id: string) => {
        Modal.error({
          title: '提示',
          content: '交货单删除后无法恢复，确定要删除吗？',
          titleAlign: 'start',
          cancelText: '取消',
          hideCancel: false,
          onOk: async () => {
            const res: any = await cancelSupplierDeliveryOrder({ ids: [id] })
            if (res.code == 'SUCCESS') {
              Message.success('删除成功')
              getList()
            }
          },
        })
      }

      const toDetail = (item: any) => {
        data.info = item
        deliveryOrderDetail.value.visible = true
      }

      const getSpecName = (info: any) => {
        let item: any = info ? JSON.parse(info.productSpecs) : []
        return item.map((e: any) => e.valueCn).join(',')
      }

      watch(
        () => props.currentIndex,
        () => {
          setTimeout(() => {
            data.pageNation.pageNum = 1
            getList()
          }, 200)
        }
      )

      getWareHouseList()
      getList()
      return {
        ...(toRefs(data) as any),
        changePage,
        sizeChange,
        searchByVal,
        spanMethodAll,
        getList,
        handleSelect,
        allocateGoods,
        editDeliveryOrder,
        submitOutHouse,
        deliveryOrderDetail,
        toDetail,
        getSpecName,
      }
    },
  })
</script>

<style lang="less" scoped>
  :deep(.arco-table-td) {
    background-color: var(--color-fill-1);
  }
  :deep(.arco-table-tr-expand) {
    .arco-table-cell {
      padding: 0;
    }
    .arco-table {
      margin: 0 !important;
      .arco-table-td {
        border-bottom: 1px solid var(--color-neutral-3);
      }
    }
    background-color: #fff !important;
  }
  :deep(.child-row) {
    .arco-table-cell {
      padding: 2px 8px;
    }
  }
  :deep(.arco-table-tr-expand .arco-table-td) {
    background-color: #fff !important;
    border-bottom: none;
  }
  :deep(.arco-table-tr-expand tr:hover .arco-table-td) {
    background-color: var(--color-fill-1) !important;
  }
  :deep(.arco-table-expand .arco-table-cell) {
    display: none;
  }
  :deep(.arco-tabs-nav-tab) {
    background-color: #fff;
  }

  .supplier-order-con {
    height: calc(100vh - @menuAndTabHeight);
    width: 100%;

    .arco-spin,
    .arco-scrollbar {
      height: 100%;
      width: 100%;
    }

    .my-table {
      .table-title {
        height: 40px;
      }
    }
  }
</style>
